import React, { useEffect } from 'react';
import { Button, Form, Input, message, Spin } from 'antd';
import { connect } from 'umi';
import { useTablePipeline } from 'ali-react-table';
import { HttpCode } from '#/utils/contacts.js';
import { useDebounceFn } from 'ahooks';
import styles from './index.less';
import { getColumns } from '../helper';
import { useTRState } from '#/utils/trHooks';
import { AntdBaseTable } from '@/base/TBaseTable';
import ApplyModal from '../components/editModel/index';
import { machineInfo, machineInfoAdd, machineInfoEdit, machineInfoDel } from '../service';
const fanSpeed = ({ menuCode, buttonPermissions }) => {
  const [state, setState] = useTRState({
    dataSource: [],
    rowData: {},
    applyType: 'add',
    showApply: false,
    loading: false,
    buttonPower: {
      add: false,
      edit: false,
      delete: false,
    },
  });
  const [form] = Form.useForm();
  useEffect(async () => {
    fetch();
    let buttonPower = { add: false, edit: false, delete: false };
    buttonPermissions.map((item) => {
      if (item.menuCode == 'UnitTypeAdd') buttonPower.add = true;
      if (item.menuCode == 'UnitTypeEdit') buttonPower.edit = true;
      if (item.menuCode == 'UnitTypeDel') buttonPower.delete = true;
    });
    setState({
      buttonPower,
    });
  }, []);
  const fetch = async (param = {}) => {
    setState({
      loading: true,
    });
    const res = await machineInfo({ ...param, size: 999 });
    if (res?.statusCode === HttpCode.SUCCESS) {
      setState({
        dataSource: res.data,
      });
    } else {
      message.error(res?.message);
    }
    setState({
      loading: false,
    });
  };
  const _onReset = useDebounceFn(
    () => {
      form.resetFields();
      fetch();
    },
    { wait: 500 },
  );
  const _onFinish = useDebounceFn(
    (values) => {
      fetch(values);
    },
    { wait: 500 },
  );
  const rowClick = async (type, row = []) => {
    if (!state.buttonPower[type]) {
      return message.info('请联系管理员获取相关权限');
    }
    if (type == 'edit' || type == 'add') {
      setState({
        applyType: type,
        rowData: row,
        showApply: true,
      });
    } else {
      setState({
        loading: true,
      });
      const res = await machineInfoDel([row.id]);
      if (res?.statusCode === HttpCode.SUCCESS) {
        message.success('删除成功！');
        fetch();
      } else {
        message.error(res?.message);
      }
      setState({
        loading: false,
      });
    }
  };
  const save = (values) => {
    let forms = { ...values };
    if (state.applyType == 'edit') {
      forms = { ...state.rowData, ...forms };
      delete forms.createBy;
      delete forms.createTime;
      delete forms.updateTime;
      delete forms.updateBy;
    }
    return state.applyType == 'add' ? machineInfoAdd([forms]) : machineInfoEdit([forms]);
  };
  const pipeline = useTablePipeline({ components: {} })
    .input({
      dataSource: state.dataSource,
      columns: getColumns({ type: 'fanSpeed', onChange: rowClick, buttonPower: state.buttonPower }),
    })
    .primaryKey('id');

  const _renderHeader = () => {
    return (
      <div className={styles.header}>
        <Form form={form} className={styles.formStyles} onFinish={_onFinish.run} autoComplete="off">
          <Form.Item name="unitType" className={styles.cell_item}>
            <Input placeholder="请输入机组类型" />
          </Form.Item>
          <Button className={styles.submit} type="primary" htmlType="submit">
            查询
          </Button>
          {/* </Popconfirm> */}
          <Button className={styles.reset} htmlType="reset" onClick={_onReset.run} ghost>
            重置
          </Button>
        </Form>
        <Button
          className={[styles.reset, !state.buttonPower['add'] ? styles.disableBtn : '']}
          htmlType="primary"
          onClick={() => rowClick('add')}
        >
          新增
        </Button>
      </div>
    );
  };
  return (
    <div>
      {_renderHeader()}
      <Spin spinning={state.loading}>
        <AntdBaseTable
          className={['bordered', 'dark', `${styles.custor}`].join(' ')}
          style={{
            // '--header-bgcolor': '#383C3E',
            '--header-color': 'white',
            '--row-height': '22px',
            '--header-row-height': '58px',
            '--bgcolor': '#222629',
            '--color': '#D3D4D4',
            '--cell-padding': '3px 16px',
            '--hover-bgcolor': '#222629',
          }}
          {...pipeline.getProps()}
          defaultColumnWidth={81}
          useVirtual={{ horizontal: false, vertical: true, header: false }}
        />
      </Spin>
      <ApplyModal
        showApply={state.showApply}
        onClose={(bool = false) => {
          setState({ showApply: false });
          if (bool) {
            fetch();
          }
        }}
        onOk={save}
        type="fan"
        data={state.rowData}
        applyType={state.applyType}
      />
    </div>
  );
};
export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(fanSpeed);
